package com.scoy.honeymei.fragment.mall;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.HttpParams;
import com.scoy.honeymei.R;
import com.scoy.honeymei.activity.mall.OrderDetailActivity;
import com.scoy.honeymei.adapter.MallMeAdapter;
import com.scoy.honeymei.base.BaseFragment;
import com.scoy.honeymei.bean.GoodsOrderBean;
import com.scoy.honeymei.bean.MallOrderBean;
import com.scoy.honeymei.dialog.EvaDialog;
import com.scoy.honeymei.http.HpCallback;
import com.scoy.honeymei.http.HpGo;
import com.scoy.honeymei.url.ApiCallBack;
import com.scoy.honeymei.url.MeConstant;
import com.scoy.honeymei.url.MyUrl;
import com.scoy.honeymei.utils.IntentUtil;
import com.scoy.honeymei.utils.MyUtil;
import com.scoy.honeymei.utils.SPHelper;
import com.scoy.honeymei.utils.SystemUtil;
import com.scoy.honeymei.wxapi.PayEvent;
import com.scoy.honeymei.wxapi.PayUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * @ClassName: CouponFragment$
 * @Description: 商城订单fragment
 * @Author: GaoZhan
 * @CreateDate: 2019/9/4/0004$ 上午 10:52$
 * @UpdateUser: 更新者
 * @UpdateDate: 2019/9/4/0004$ 上午 10:52$
 * @UpdateRemark: 更新内容
 */
public class MallMeFragment extends BaseFragment {


    @BindView(R.id.normal_rv)
    RecyclerView normalRv;
    @BindView(R.id.nodata_tv)
    TextView nodataTv;
    @BindView(R.id.nor_srl)
    SmartRefreshLayout norSrl;
    private int type;
    private Unbinder unbinder;
    private Context mContext;
    private ArrayList<MallOrderBean> datalist;
    private MallMeAdapter mallMeAdapter;
    private int pageInt;
    private String payType = "null";
    private String payThree;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
    }

    public static MallMeFragment newInstance(int type) {
        Bundle args = new Bundle();
        args.putInt("type", type);
        MallMeFragment fragment = new MallMeFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.custom_fragment_list, null, false);
        unbinder = ButterKnife.bind(this, view);
        mContext = getContext();

        initNormal();

        httpmalllist(0);

        return view;
    }

    @Override
    public void initNormal() {
        datalist = new ArrayList<>();

        initRV();

        norSrl.setOnRefreshListener(refreshLayout -> {
            refreshLayout.finishRefresh(1500);
            datalist.clear();
            httpmalllist(0);
        }).setOnLoadMoreListener(refreshLayout -> {
            refreshLayout.finishLoadMore(1500);
            httpmalllist(pageInt);
        });

        EventBus.getDefault().register(this);

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    private void initRV() {
        mallMeAdapter = new MallMeAdapter(mContext, datalist, nodataTv, type);
        normalRv.setLayoutManager(new LinearLayoutManager(mContext, RecyclerView.VERTICAL, false));
        normalRv.setAdapter(mallMeAdapter);
        mallMeAdapter.setOnOneClick(pos -> {
            MallOrderBean mallOrderBean = datalist.get(pos);
            int id = mallOrderBean.getId();
            Intent intent0 = new Intent(mContext, OrderDetailActivity.class);
            intent0.putExtra("type", type);
            intent0.putExtra("oId", id);
            startActivityForResult(intent0, 0x14);
        });

        //cancle
        mallMeAdapter.setOnTwoClick(pos -> {
            MallOrderBean mallOrderBean = datalist.get(pos);
            int id = mallOrderBean.getId();
            new AlertDialog.Builder(mContext).setTitle("确认取消该订单？")
                    .setNegativeButton("取消", null)
                    .setPositiveButton("确认", (dialog, which) -> {
                        httpCancle(id);
                    }).show();
        });

        //btn
        mallMeAdapter.setOnThreeClick(pos -> {
            MallOrderBean mallOrderBean = datalist.get(pos);
            int id = mallOrderBean.getId();
            if (type == 1) {
                new AlertDialog.Builder(mContext).setTitle("确认已收货？")
                        .setNegativeButton("取消", null)
                        .setPositiveButton("确认", (dialog, which) -> {
                            httpSure(id);
                        }).show();
            } else if (type == 2) {//评价
                List<MallOrderBean.GoodsListBean> mData = mallOrderBean.getGoodsList();

                ArrayList<GoodsOrderBean> mDataTt = new ArrayList<>();
                for (MallOrderBean.GoodsListBean aBean : mData) {
                    mDataTt.add(new GoodsOrderBean(aBean.getId(), aBean.getImage(), aBean.getName(), aBean.getMoney(), 0));
                }
                EvaDialog.newInstance(mallOrderBean.getId(), mallOrderBean.getShop_id(), mallOrderBean.getShop_name(), mDataTt)
                        .setOnDialogListener(() -> {
                            norSrl.autoRefresh();
                        })
                        .show(getChildFragmentManager(), "");
            } else {
                showdialog(mallOrderBean.getId() + "");

            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 0x47:
                norSrl.autoRefresh();
                break;
        }
    }

    private void httpmalllist(int myPage) {
        HttpParams params = new HttpParams();
        params.put("userid", SPHelper.getString(MeConstant.UID, ""));
        params.put("page", myPage);
        params.put("status", type + 1);//	1是待付款订单 2是待收货 3是已完成
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.MALL_ORDER_LIST, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                List<MallOrderBean> data = new Gson().fromJson(o, new TypeToken<List<MallOrderBean>>() {
                }.getType());
                if (data != null && data.size() > 0) {
                    MallOrderBean mallOrderBean = data.get(0);
                    payThree = mallOrderBean.getPaytype();
                }
                pageInt = myPage + 1;
                datalist.addAll(data);
                mallMeAdapter.notifyDataSetChanged();
            }
        });

    }

    private void httpCancle(int orderid) {
        HttpParams params = new HttpParams();
        params.put("orderid", orderid);
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.MALL_ORDER_DELETE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                MyUtil.mytoast(mContext, "删除成功");
                norSrl.autoRefresh();
            }

        });

    }

    private void httpSure(int orderid) {
        HttpParams params = new HttpParams();
        params.put("orderid", orderid);
        HpGo.newInstance().HttpGo(getActivity(), MyUrl.MALL_ORDER_SURE, params, new ApiCallBack() {
            @Override
            public void onSuccess(String o) {
                norSrl.autoRefresh();
            }

        });

    }

    /**
     * 选择弹窗
     */
    private void showdialog(String oId) {
        final Dialog dialogpay = new Dialog(mContext, R.style.BottomDialogStyle);
        View view = View.inflate(mContext, R.layout.dialog_tocheckpay_wallet, null);

        ImageView imgClose = view.findViewById(R.id.imgClose);
        Button btnSure = view.findViewById(R.id.btnSure);
        TextView alipayTv = view.findViewById(R.id.txtZhifubao);
        TextView wxpayTv = view.findViewById(R.id.txtWechat);
        TextView walletTv = view.findViewById(R.id.txtWallet);

        dialogpay.setOnDismissListener(dialog -> payType = "null");

        imgClose.setOnClickListener(view12 -> dialogpay.dismiss());
        alipayTv.setOnClickListener(v -> {
            alipayTv.setSelected(true);
            wxpayTv.setSelected(false);
            walletTv.setSelected(false);
            payType = "alipay";
        });
        walletTv.setOnClickListener(v -> {
            walletTv.setSelected(true);
            wxpayTv.setSelected(false);
            alipayTv.setSelected(false);
            payType = "balance";
        });
        wxpayTv.setOnClickListener(v -> {
            alipayTv.setSelected(false);
            wxpayTv.setSelected(true);
            walletTv.setSelected(false);
            payType = "wechat";
        });


        btnSure.setOnClickListener(view1 -> {
            if (!"null".equals(payType)) {
                if ("wechat".equals(payType) || "alipay".equals(payType)) {
                    payOrder(oId, payType);
                } else if ("balance".equals(payType)) {
                    payBalance(oId, payType);
                }
                dialogpay.dismiss();
            }
        });

        dialogpay.setContentView(view);
        dialogpay.setCanceledOnTouchOutside(true);
        Window dialogWindow = dialogpay.getWindow();
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (SystemUtil.getScreenWidth(mContext));
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.gravity = Gravity.BOTTOM;
        dialogWindow.setAttributes(lp);
        dialogpay.show();

    }

    //订单未支付支付
    private void payOrder(String oId, String payType) {
        HttpParams params = new HttpParams();
        params.put("orderid", oId);
        params.put("type", payType);

        HpGo.newInstance().HttpGo(getActivity(), MyUrl.ORDER_PAY_ORDER, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                // payThree  1  三方； 2  原生
                if ("2".equals(payThree)) {
                    if ("false".equals(o)) {
                        MyUtil.mytoast(mContext, "支付错误");
                        return;
                    }
                    PayUtil.toPayPayPay(getActivity(), payType, o);//支付
                } else {
                    if ("alipay".equals(payType)) {
                        IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_ALIPAY + o);
                        getActivity().finish();
                    } else {
                        if ("false".equals(o)) {
                            MyUtil.mytoast(mContext, "支付错误");
                            return;
                        }
                        PayUtil.toPayPayPay(getActivity(), payType, o);//支付
                        //  IntentUtil.openAPP(mContext, MyUrl.APP_OPEN_WX + o);
                    }

                }
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, code + "," + msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    private void payBalance(String oId, String payType) {
        HttpParams params = new HttpParams();
        params.put("orderid", oId);

        HpGo.newInstance().HttpGo(getActivity(), MyUrl.ORDER_PAY_BALANCE, params, new HpCallback() {
            @Override
            public void onSuccess(String o) {
                MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
                norSrl.autoRefresh();
            }

            @Override
            public void onFailed(String code, String msg, String o) {
                MyUtil.mytoast(mContext, msg);
            }

            @Override
            public void onError(int code, String errorMsg) {
                MyUtil.mytoast(mContext, errorMsg);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPayEvent(PayEvent event) {
        int type = event.getType();//0 成功 -1失败 -2取消
        if (type == 0) {
            MyUtil.mytoast0(mContext, "支付成功", R.mipmap.ic_sure);
            norSrl.autoRefresh();
        } else if (type == -1) {
            MyUtil.mytoast(mContext, "支付失败");
        } else {
            MyUtil.mytoast(mContext, "支付取消");
        }
    }


}
